package com.lmx.smsmonitor;

import android.Manifest;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.lmx.smsmonitor.util.Const;
import com.lmx.smsmonitor.util.SharedPreUtil;
import com.lmx.smsmonitor.view.EmailAutoCompleteTextView;
import com.permissionx.guolindev.PermissionX;

import org.apache.commons.lang3.StringUtils;

public class MainActivity extends AppCompatActivity {

    private EmailAutoCompleteTextView eacSenderAccount;
    private EditText etSenderPassword;
    private EmailAutoCompleteTextView eacReceiverAccount;
    private Button btnSetting;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        initEvent();

    }

    private void initView() {
        eacSenderAccount = findViewById(R.id.eac_sender_account);
        etSenderPassword = findViewById(R.id.et_sender_password);
        eacReceiverAccount = findViewById(R.id.eac_receiver_account);
        btnSetting = findViewById(R.id.btn_setting);

        eacSenderAccount.setText(((String) SharedPreUtil.getData(Const.KEY_SENDER_ACCOUNT, "")));
        etSenderPassword.setText(((String) SharedPreUtil.getData(Const.KEY_SENDER_PASSWORD, "")));
        eacReceiverAccount.setText(((String) SharedPreUtil.getData(Const.KEY_RECEIVER_ACCOUNT, "")));
    }

    private void initEvent() {
        btnSetting.setOnClickListener(v -> {
            requestPermission();

            String senderAccount = eacSenderAccount.getText().toString();
            String senderPassword = etSenderPassword.getText().toString();
            String receiverAccount = eacReceiverAccount.getText().toString();

            if (StringUtils.isBlank(senderAccount) || StringUtils.isBlank(senderPassword)
                    || StringUtils.isBlank(receiverAccount)) {
                Toast.makeText(this, "信息不能为空喔！", Toast.LENGTH_SHORT).show();
                return;
            }

            if (SharedPreUtil.putData(Const.KEY_SENDER_ACCOUNT, senderAccount)
                    && SharedPreUtil.putData(Const.KEY_SENDER_PASSWORD, senderPassword)
                    && SharedPreUtil.putData(Const.KEY_RECEIVER_ACCOUNT, receiverAccount)) {
                finish();
                Toast.makeText(this, "设置成功！", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "设置失败！", Toast.LENGTH_SHORT).show();
            }

        });
    }

    private void requestPermission() {
        PermissionX.init(this)
                .permissions(Manifest.permission.RECEIVE_SMS)
                .request(((allGranted, grantedList, deniedList) -> {
                    if (!allGranted) {
                        Toast.makeText(this, "你拒绝了权限，短信转发功能无法启用", Toast.LENGTH_SHORT).show();
                    }
                }));
    }
}